let pc = null;
let isStarted = false;
let initializeAttempts = 0;
const maxInitializeAttempts = 10;
const initializeInterval = 500; // 500ms
let isInitialized = false;
let mediaRecorder = null;
let hasAudio = false;
let hasVideo = false;

function initialize() {
    if (window.webrtcBridge) {
        isInitialized = true;
        // 初始化完成后设置 webrtcPlayer
        window.webrtcPlayer = {
            play: play,
            stop: stop,
            startRecording: startRecording,
            stopRecording: stopRecording
        };
        return;
    }
    
    if (initializeAttempts >= maxInitializeAttempts) {
        return;
    }
    
    initializeAttempts++;
    setTimeout(initialize, initializeInterval);
}

// 确保 WebChannel 初始化完成后再初始化 WebRTC
if (typeof QWebChannel !== 'undefined') {
    initialize();
} else {
    document.addEventListener('DOMContentLoaded', () => {
                                  console.log('DOMContentLoaded, waiting for QWebChannel...');
                                  const checkQWebChannel = setInterval(() => {
                                                                           if (typeof QWebChannel !== 'undefined') {
                                                                               clearInterval(checkQWebChannel);
                                                                               initialize();
                                                                           }
                                                                       }, 100);
                              });
}

function negotiate() {
    if (window.webrtcBridge) {
        window.webrtcBridge.updateConnectionState("connecting");
    }
    pc.addTransceiver('video', { direction: 'recvonly' });
    pc.addTransceiver('audio', { direction: 'recvonly' });

    return pc.createOffer()
    .then(offer => {
              return pc.setLocalDescription(offer);
          })
    .then(() => {
              return new Promise(resolve => {
                                     if (pc.iceGatheringState === 'complete') {
                                         resolve();
                                     } else {
                                         function checkState() {
                                             if (pc.iceGatheringState === 'complete') {
                                                 pc.removeEventListener('icegatheringstatechange', checkState);
                                                 resolve();
                                             }
                                         }
                                         pc.addEventListener('icegatheringstatechange', checkState);
                                     }
                                 });
          })
    .then(() => {
              const offer = pc.localDescription;

              return new Promise((resolve, reject) => {
                                     if (!window.webrtcBridge.serverUrl) {
                                         reject(new Error('Server URL is not set'));
                                         return;
                                     }


                                     window.webrtcBridge.sendOffer(JSON.stringify({
                                                                                      sdp: offer.sdp,
                                                                                      type: offer.type,
                                                                                      url: window.webrtcBridge.serverUrl
                                                                                  }));

                                     window.webrtcBridge.offerResponse.connect(function(response) {
                                         try {
                                             const answer = JSON.parse(response);
                                             resolve(answer);
                                         } catch (e) {
                                             reject(new Error('Invalid JSON response'));
                                         }
                                     });

                                     // window.webrtcBridge.error.connect(function(errorMessage) {
                                     //     reject(new Error(errorMessage));
                                     // });
                                 });
          })
    .then(answer => {
              console.log('Received answer from server:', answer);
              return pc.setRemoteDescription(answer);
          })
    .catch(e => {
               console.error('Error during negotiation:', e);
               isStarted = false;
               if (window.webrtcBridge) {
                   window.webrtcBridge.updateConnectionState("failed");
               }
           });
}

function play() {
    try {
        console.log('WebRTC play 开始执行');
        if (isStarted) {
            return;
        }
        
        isStarted = true;

        const config = {
            sdpSemantics: 'unified-plan',
            iceServers: [{ urls: ['stun:stun.l.google.com:19302'] }]
        };

        pc = new RTCPeerConnection(config);

        hasAudio = false;
        hasVideo = false;
        pc.addEventListener('iceconnectionstatechange', () => {
                                try {
                                    if (window.webrtcBridge) {
                                        window.webrtcBridge.updateConnectionState(pc.iceConnectionState);
                                    }
                                    if (pc.iceConnectionState === 'failed' || pc.iceConnectionState === 'disconnected') {

                                        stop();
                                    }
                                } catch (error) {
                                }
                            });

        pc.addEventListener('track', evt => {
                                console.log('Received track:', evt.track.kind);
                                if (evt.track.kind === 'video') {
                                    const videoElem = document.getElementById('video');
                                    videoElem.srcObject = evt.streams[0];
                                    hasVideo = true;

                                    videoElem.onloadedmetadata = () => {
                                        console.log('Video metadata loaded');
                                        videoElem.play().catch(e => console.error('Error playing video:', e));
                                    };
                                } else if (evt.track.kind === 'audio') {
                                    const audioElem = document.getElementById('audio');
                                    audioElem.srcObject = evt.streams[0];
                                    hasAudio = true;
                                }
                            });

        negotiate();
    } catch (error) {
        console.error('WebRTC play 错误:', error);
        if (window.webrtcBridge) {
            window.webrtcBridge.error(error.toString());
        }
    }
}

function stop() {
    if (!isStarted) return;
    isStarted = false;

    try {
        if (pc) {
            pc.close();
            pc = null;
        }

        const videoElem = document.getElementById('video');
        const audioElem = document.getElementById('audio');
        
        if (videoElem) {
            videoElem.pause();
            videoElem.srcObject = null;
        }
        
        if (audioElem) {
            audioElem.pause();
            audioElem.srcObject = null;
        }
        if (window.webrtcBridge) {
            window.webrtcBridge.updateConnectionState("stoped");
        }

    } catch (error) {
        console.error('Error in stop:', error);
    }
}

// 在 initialize 函数中添加全局错误处理
window.onerror = function(message, source, lineno, colno, error) {
    console.error('Global error:', {message, source, lineno, colno, error});
    if (window.webrtcBridge) {
        window.webrtcBridge.error('JavaScript error: ' + message);
    }
};

// 添加一个辅助函数来分块处理大数据
function arrayBufferToBase64Chunked(buffer) {
    const uint8Array = new Uint8Array(buffer);
    const chunkSize = 0x8000; // 32KB chunks
    let base64 = '';
    
    for (let i = 0; i < uint8Array.length; i += chunkSize) {
        const chunk = uint8Array.slice(i, Math.min(i + chunkSize, uint8Array.length));
        base64 += String.fromCharCode.apply(null, chunk);
    }
    
    return btoa(base64);
}

// 修改录制相关的代码
function startRecording() {
    try {
        // 确保之前的 mediaRecorder 已经清理
        if (mediaRecorder) {
            try {
                mediaRecorder.stop();
            } catch (e) {
                console.warn('Error stopping previous MediaRecorder:', e);
            }
            mediaRecorder = null;
        }

        if (!pc || !pc.getReceivers) {
            return false;
        }

        var videoTrack = null;
        var audioTrack = null;
        var receivers = pc.getReceivers();
        for (var i = 0; i < receivers.length; i++) {
            if (receivers[i].track) {
                if (receivers[i].track.kind === 'video') {
                    videoTrack = receivers[i].track;
                } else if (receivers[i].track.kind === 'audio') {
                    audioTrack = receivers[i].track;
                }
            }
        }

        if (!videoTrack && !audioTrack) {
            return false;
        }

        var tracks = [];
        if (videoTrack && hasVideo) tracks.push(videoTrack);
        if (audioTrack && hasAudio) tracks.push(audioTrack);

        var stream = new MediaStream(tracks);

        // 创建 MediaRecorder，增加比特率以提高质量
        mediaRecorder = new MediaRecorder(stream, {
                                              mimeType: 'video/webm;codecs=vp8,opus',
                                              videoBitsPerSecond: 4000000, // 4Mbps
                                              audioBitsPerSecond: 128000  // 128kbps
                                          });

        // 通知 Qt 创建新文件
        var pendingData = [];  // 用于临时存储数据

        // 每200ms触发一次 ondataavailable，更频繁的数据记录
        mediaRecorder.ondataavailable = function(event) {
            if (event.data && event.data.size > 0) {
                // 将数据添加到待处理队列
                pendingData.push(event.data);
                
                var reader = new FileReader();
                reader.onload = function() {
                    var array = new Uint8Array(reader.result);
                    var base64Data = '';
                    for(var i = 0; i < array.length; i++) {
                        base64Data += String.fromCharCode(array[i]);
                    }
                    base64Data = btoa(base64Data);
                    
                    // 将数据追加到文件
                    if (window.webrtcBridge) {
                        window.webrtcBridge.saveRecording(base64Data);
                    }
                };

                reader.onerror = function(error) {
                    if (window.webrtcBridge) {
                        window.webrtcBridge.updateConnectionState('recording fail');
                    }
                };

                reader.readAsArrayBuffer(event.data);
            }
        };

        // 在停止时确保所有数据被保存
        mediaRecorder.onstop = function() {
            // 处理所有待处理的数据
            while (pendingData.length > 0) {
                var data = pendingData.shift();
                try {
                    var reader = new FileReader();
                    reader.onload = function() {
                        var array = new Uint8Array(reader.result);
                        var base64Data = '';
                        for(var i = 0; i < array.length; i++) {
                            base64Data += String.fromCharCode(array[i]);
                        }
                        base64Data = btoa(base64Data);
                        
                        if (window.webrtcBridge) {
                            window.webrtcBridge.saveRecording(base64Data);
                        }
                    };
                    reader.readAsArrayBuffer(data);
                } catch (e) {
                    console.warn('Error processing final data:', e);
                }
            }
            
            // 请求最后一块数据
            try {
                mediaRecorder.requestData();
            } catch (e) {
                console.warn('Error requesting final data:', e);
            }
        };
        
        mediaRecorder.start(200); // 每200ms触发一次 ondataavailable
        if (window.webrtcBridge) {
            window.webrtcBridge.updateConnectionState('recording success');
        }
        return true;

    } catch (error) {
        console.error('Error in startRecording:', error);
        if (window.webrtcBridge) {
            window.webrtcBridge.updateConnectionState('recording fail');
        }
        mediaRecorder = null;
        return false;
    }
}

function stopRecording() {
    try {
        if (!mediaRecorder || mediaRecorder.state === 'inactive') {
            return false;
        }
        mediaRecorder.stop();
        // 清理 mediaRecorder
        mediaRecorder = null;
        return true;
    } catch (error) {
        // 即使出错也要清理 mediaRecorder
        mediaRecorder = null;
        return false;
    }
}

// 导出接口供 Qt 调用
window.webrtcPlayer = {
    play: play,
    stop: stop,
    startRecording: startRecording,
    stopRecording: stopRecording
};
